/**
 * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gang.ssm.bos.core.shiro;

import java.util.List;

import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;

import com.gang.ssm.bos.common.ShiroUser;
import com.gang.ssm.bos.core.interfaces.IShiro;
import com.gang.ssm.bos.system.bean.User;
import com.gang.ssm.bos.system.service.MenuService;
import com.gang.ssm.bos.system.service.RoleService;
import com.gang.ssm.bos.system.service.UserService;



public class DefaultShiroFactroy implements IShiro {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private MenuService menuService;
	
	public User user(String username) {
		User user = userService.findByUsername(username);
		// 账号不存在
		if (null == user) {
			throw new UnknownAccountException();
		}
		
		return user;
	}

	public ShiroUser shiroUser(User user) {
		
		List<Integer> roleIdList = roleService.findIdListByUserId(user.getId());
		return new ShiroUser(user.getId(), user.getUsername(), roleIdList);
	}

	public List<String> findPermissionsByRoleId(Integer roleId) {
		
		return menuService.findUrlByRoleId(roleId);
	}

	public String findRoleNameByRoleId(Integer roleId) {
		
		return roleService.findRoleCodeByRoleId(roleId);
	}

	public SimpleAuthenticationInfo info(ShiroUser shiroUser, User user, String realmName) {
		String credentials = user.getPassword();
		// 密码加盐处理SimpleAuthenticationInfo
		return new SimpleAuthenticationInfo(shiroUser, credentials, realmName);
	}

}
